import React, { useRef, useState, useEffect } from "react";
import { Canvas } from "@react-three/fiber";
import { useLoader, useFrame } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { AnimationMixer, AnimationClip, AmbientLight, PointLight, SpotLight } from "three";
// import './style/ThreeScene1.css'
// 为 AnimatedModel 组件的 props 添加类型
interface AnimatedModelProps {
  modelPath: string;
}

const AnimatedModel: React.FC<AnimatedModelProps> = ({ modelPath }) => {
  // 加载 GLTF 模型及动画数据
  const gltf = useLoader(GLTFLoader, modelPath);

  // 使用 useRef 存储 AnimationMixer
  const mixer = useRef<AnimationMixer>(new AnimationMixer(gltf.scene));

  // 使用 useState 存储动画数据
  const [animations] = useState<AnimationClip[]>(gltf.animations);

  // 灯光 环境光
  const light = new AmbientLight(0xff0000, 1);
  gltf.scene.add(light);

  /* 点光源 */
  const light1 = new PointLight(0xFFFFFF, 5, 1);
  gltf.scene.add(light1);

  /* 聚光灯 */
  const light2 = new SpotLight(0xFFFFFF, 1, 100);
  gltf.scene.add(light2);



  // 使用 useEffect 设置动画播放
  useEffect(() => {
    if (animations && animations.length > 0) {
      animations.forEach((clip) => mixer.current.clipAction(clip).play());
    }
  }, [animations]);

  // 在每一帧更新动画
  useFrame((state, delta) => mixer.current.update(delta));

  return (
    <primitive object={gltf.scene} position={[0, -2.7, 0]} scale={[3.3, 3.3, 3.3]} />
  );
};

const App: React.FC = () => {
  return (
    <Canvas className="canvas">
      {/* 环境光 */}
      <ambientLight intensity={0.5} />

      {/* 平行光 */}
      <directionalLight position={[10, 10, 10]} intensity={1} />

      {/* 点光源 */}
      <pointLight position={[5, 5, 5]} intensity={1} distance={10} />

      {/* 聚光灯 */}
      <spotLight position={[0, 5, 0]} angle={0.3} intensity={2} castShadow />

      {/* 模型 */}
      <AnimatedModel modelPath="/models/zxfa.glb" />

      {/* 控制器 */}
      <OrbitControls />
    </Canvas>
  );
};

export default App;